const db = wx.cloud.database()
const _ = db.command
const cache = require('../utils/cache')
const toast = require('../utils/toast')
const MESSAGE = require('../config/message.config')
const md5 = require('../utils/md5.js')
// 调用云函数
const getOpenID = () => {
  const openid = cache.getOpenID()
  return new Promise((resolve, reject) => {
    if (openid) resolve(openid)
    wx.cloud.callFunction({
        name: 'login',
      })
      .then(res => {
        cache.setOpenID(res.result.openid)
        resolve(res.result.openid)
      })
      .catch(err => {
        reject(err)
      })
  })
}

const login = (loginData) => {
  let whereData;
  if (!loginData) {
    const openid = cache.getOpenID()
    if (!openid) throw new Error(MESSAGE.ERROR_MESSAGE.IDENTITYEXPIRED);
    whereData = {
      _openid: openid
    }
  } else {
    whereData = {
      account: loginData.account
    }

  }
  return new Promise((resolve, reject) => {
    //登录之前是否已经授权注册
    toast.showLoading('登录中')
    const _openid = cache.getOpenID()
    db.collection('userInfo').where(whereData).get({
      success: res => {
        toast.hideLoading()
        if (res.data[0]) {
          console.log('查询登录用户的信息', res.data[0]);
          console.log('_openid', _openid);
          // 判断登录用户使用的账号密码是否是该用户的，这里用openid判断
          if (_openid != res.data[0]._openid) {
            toast.showToast(MESSAGE.ERROR_MESSAGE.LOGINFAIL)
            return
          }
          const userInfo = JSON.parse(JSON.stringify(res.data[0]))
          console.log('用户信息', userInfo);
          if (loginData) {
            // 判断密码是否一致
            if (md5.hexMD5(loginData.password) === userInfo.password) {
              // 一致
              toast.showToast(MESSAGE.SUCCESS.LOGINSUCCESS)
              delete userInfo.password
              delete userInfo._openid
              cache.setCache('get_identityId', userInfo.identityId)
              cache.setUserInfo(userInfo)
              resolve()
            } else {
              toast.showToast(MESSAGE.ERROR_MESSAGE.LOGINFAIL)
              reject()
            }
          }

          delete userInfo.password
          delete userInfo._openid
          cache.setCache('get_identityId', userInfo.identityId)
          cache.setUserInfo(userInfo)
          resolve()

        } else {

          toast.showToast(MESSAGE.ERROR_MESSAGE.NOREGISTE)
          reject(1)
        }
      }
    })
  })

}

const registe = (formData) => {
  if (!formData) return
  const openid = cache.getOpenID()
  if (!openid) throw new Error(MESSAGE.ERROR_MESSAGE.IDENTITYEXPIRED);
  formData.account = Number(formData.account)
  console.log('formData', formData);
  return new Promise((resolve, reject) => {
    db.collection('userInfo').where(_.or([{
        account: _.eq(formData.account)
      },
      {
        _openid: _.eq(openid)
      }
    ])).get({
      success: async res => {
        console.log('让我看看这是什么', res.data[0])
        //原先没有添加，这里添加
        if (!res.data[0]) {
          //将数据添加到数据库
          const data = {
            avatarUrl: formData.wxUser.avatarUrl,
            nickName: formData.wxUser.nickName,
            namePinyin: "",
            email: formData.email,
            account: Number(formData.account),
            password: md5.hexMD5(formData.papassword),
            identityId: formData.identityId,
            collegeId: formData.collegeId,
            gender: Number(formData.gender),
            permissions: formData.identityId == 'Administrator' ? true : false
          }
          const user = await addUserInfo(data)
          resolve(user)
        } else {
          if (formData.account == res.data[0].account) {
            toast.showToast(MESSAGE.ERROR_MESSAGE.REGISTETOACCOUNT)
          } else {
            toast.showToast(MESSAGE.ERROR_MESSAGE.REGISTETOLOGIN)
            resolve(-1)
          }

        }

      },
      fail(err) {
        reject(err)
      }
    })
  })

}

const addUserInfo = (formData) => {
  return new Promise((resolve, reject) => {
    db.collection('userInfo').add({
      data: formData,
      success: res => {
        console.log(res)
        toast.showToast(MESSAGE.SUCCESS.REGISTESUCCESS)
        resolve(res)
      },
      fail(err) {
        toast.showToast(MESSAGE.ERROR_MESSAGE.REGISTEFAIL + err.message)
        reject(err)
      }
    })
  })

}

module.exports = {
  getOpenID,
  login,
  registe
}